package databases;

import java.sql.*;

/**
 * Created by pc on 2015/2/1.
 */
public class DBTest {
    public static void main(String[] args) throws ClassNotFoundException {
        System.out.println("-------- MySQL JDBC Connection Testing ------------");
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            System.out.println("Where is your MySQL JDBC Driver?");
            e.printStackTrace();
            return;
        }

        System.out.println("MySQL JDBC Driver Registered!");
        Connection connection;
        try {
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mkyongcom", "root", "password");

        } catch (SQLException e) {
            System.out.println("Connection Failed! Check output console");
            e.printStackTrace();
            return;
        }

        if (connection != null) {
            try {
            Statement stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery("select * from test");
                while (rs.next()) {
                    // It is possible to get the columns via name
                    // also possible to get the columns via the column number
                    // which starts at 1
                    // e.g. resultSet.getSTring(2);
                    String user = rs.getString(1);
                    String website = rs.getString(2);
                    System.out.println("User: " + user);
                    System.out.println("Website: " + website);
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            System.out.println("You made it, take control your database now!");
        } else {
            System.out.println("Failed to make connection!");
        }
    }
}
